const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');

function getMultiplier(level) {
    if (level >= 1 && level <= 40) return 150;
    if (level >= 41 && level <= 70) return 200;
    if (level >= 71 && level <= 160) return 300;
    return 150;
}

function parseDocTenHourMap(docContent) {
    const lines = docContent.split(/\r?\n/);
    const map = new Map();
    for (const line of lines) {
        if (!/^\d+\s*,/.test(line)) continue; // 行以数字开头，逗号分隔
        const parts = line.split(',').map(s => s.trim());
        if (parts.length < 3) continue;
        const level = parseInt(parts[0], 10);
        const tenHourExp = Number(parts[2]);
        if (!Number.isNaN(level) && !Number.isNaN(tenHourExp)) {
            map.set(level, tenHourExp);
        }
    }
    return map;
}

async function ensureColumn(conn, dbName) {
    const [cols] = await conn.execute(
        'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1',
        [dbName, 'level_experience', 'standard_exp_per_fight']
    );
    if (cols.length === 0) {
        await conn.execute(
            "ALTER TABLE level_experience ADD COLUMN standard_exp_per_fight INT NULL COMMENT '每次标准战斗获得的经验' AFTER experience"
        );
    }
}

async function main() {
    const projectRoot = path.resolve(__dirname, '..');
    const docPath = path.join(projectRoot, 'doc', '训练经验.md');
    const doc = fs.readFileSync(docPath, 'utf8');
    const levelToTenHour = parseDocTenHourMap(doc);

    const config = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
        multipleStatements: true,
        timezone: '+08:00'
    };

    let conn;
    try {
        conn = await mysql.createConnection(config);
        await ensureColumn(conn, config.database);

        let updated = 0;
        for (const [level, tenHourExp] of levelToTenHour.entries()) {
            const m = getMultiplier(level);
            const standard = Math.floor(tenHourExp / (m * 10 * 1.1));
            if (standard > 0) {
                await conn.execute(
                    'UPDATE level_experience SET standard_exp_per_fight = ?, updated_at = NOW() WHERE level = ?',
                    [standard, level]
                );
                updated += 1;
            }
        }
        console.log(`已写入 standard_exp_per_fight 到 ${updated} 个等级`);
    } catch (e) {
        console.error('计算写入失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch((e) => {
    console.error(e);
    process.exit(1);
});
